/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.NonexistentEntityException;
import entities.Submission;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Problem;
import entities.Contest;
import entities.User;
import java.util.Vector;
import util.EnumSearchParameter;
import vo.VOSubmission;

/**
 *
 * @author sbaldrich
 */
public class SubmissionJpaController {

    public SubmissionJpaController()
    {
        emf = Persistence.createEntityManagerFactory("CMalphaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Submission submission)
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Problem problem = submission.getProblem();
            if (problem != null)
            {
                problem = em.getReference(problem.getClass(), problem.getIdProblem());
                submission.setProblem(problem);
            }
            Contest contest = submission.getContest();
            if (contest != null)
            {
                contest = em.getReference(contest.getClass(), contest.getIdContest());
                submission.setContest(contest);
            }
            User user = submission.getUser();
            if (user != null)
            {
                user = em.getReference(user.getClass(), user.getIdUser());
                submission.setUser(user);
            }
            em.persist(submission);
            if (problem != null)
            {
                problem.getSubmissionList().add(submission);
                problem = em.merge(problem);
            }
            if (contest != null)
            {
                contest.getSubmissionList().add(submission);
                contest = em.merge(contest);
            }
            if (user != null)
            {
                user.getSubmissionList().add(submission);
                user = em.merge(user);
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Submission submission) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Submission persistentSubmission = em.find(Submission.class, submission.getIdSubmission());
            Problem problemOld = persistentSubmission.getProblem();
            Problem problemNew = submission.getProblem();
            Contest contestOld = persistentSubmission.getContest();
            Contest contestNew = submission.getContest();
            User userOld = persistentSubmission.getUser();
            User userNew = submission.getUser();
            if (problemNew != null)
            {
                problemNew = em.getReference(problemNew.getClass(), problemNew.getIdProblem());
                submission.setProblem(problemNew);
            }
            if (contestNew != null)
            {
                contestNew = em.getReference(contestNew.getClass(), contestNew.getIdContest());
                submission.setContest(contestNew);
            }
            if (userNew != null)
            {
                userNew = em.getReference(userNew.getClass(), userNew.getIdUser());
                submission.setUser(userNew);
            }
            submission = em.merge(submission);
            if (problemOld != null && !problemOld.equals(problemNew))
            {
                problemOld.getSubmissionList().remove(submission);
                problemOld = em.merge(problemOld);
            }
            if (problemNew != null && !problemNew.equals(problemOld))
            {
                problemNew.getSubmissionList().add(submission);
                problemNew = em.merge(problemNew);
            }
            if (contestOld != null && !contestOld.equals(contestNew))
            {
                contestOld.getSubmissionList().remove(submission);
                contestOld = em.merge(contestOld);
            }
            if (contestNew != null && !contestNew.equals(contestOld))
            {
                contestNew.getSubmissionList().add(submission);
                contestNew = em.merge(contestNew);
            }
            if (userOld != null && !userOld.equals(userNew))
            {
                userOld.getSubmissionList().remove(submission);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld))
            {
                userNew.getSubmissionList().add(submission);
                userNew = em.merge(userNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = submission.getIdSubmission();
                if (findSubmission(id) == null)
                {
                    throw new NonexistentEntityException("The submission with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Submission submission;
            try
            {
                submission = em.getReference(Submission.class, id);
                submission.getIdSubmission();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The submission with id " + id + " no longer exists.", enfe);
            }
            Problem problem = submission.getProblem();
            if (problem != null)
            {
                problem.getSubmissionList().remove(submission);
                problem = em.merge(problem);
            }
            Contest contest = submission.getContest();
            if (contest != null)
            {
                contest.getSubmissionList().remove(submission);
                contest = em.merge(contest);
            }
            User user = submission.getUser();
            if (user != null)
            {
                user.getSubmissionList().remove(submission);
                user = em.merge(user);
            }
            em.remove(submission);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Submission> findSubmissionEntities()
    {
        return findSubmissionEntities(true, -1, -1);
    }

    public List<Submission> findSubmissionEntities(int maxResults, int firstResult)
    {
        return findSubmissionEntities(false, maxResults, firstResult);
    }

    private List<Submission> findSubmissionEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Submission.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Submission findSubmission(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Submission.class, id);
        } finally
        {
            em.close();
        }
    }

    public int getSubmissionCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Submission> rt = cq.from(Submission.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

    public ArrayList<VOSubmission> findAll(EnumSearchParameter parameter, Object o)
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createQuery("select s from Submission s Where s." + parameter.value()
                    +" = :" + parameter.value());
            q.setParameter(parameter.value(), o);
            
            ArrayList<VOSubmission> ret = new ArrayList<VOSubmission>();
            Vector<Submission> l =(Vector<Submission>)q.getResultList();
            for(Submission s : l)
                ret.add(s.getVO());
            return ret;
        } catch (Exception e)
        {
            System.out.println("Exception at SubmisionJpaController.findAll: " + e.getMessage());
            return null;
        }
    }

}
